package com.kosmian.fastid;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Supplier;

public class QPSCounter {
    private final AtomicLong counter = new AtomicLong(0);
    private volatile long lastQPS = 0;
    Runtime runtime = Runtime.getRuntime();
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    private final boolean isCountFreeInfo;

    public QPSCounter() {
        this(false);
    }

    public QPSCounter(boolean isCountFreeInfo) {
        this.isCountFreeInfo = isCountFreeInfo;
        // 每秒执行一次清零和记录QPS
        scheduler.scheduleAtFixedRate(() -> {
            lastQPS = counter.getAndSet(0); // 获取当前计数并清零
            if (isCountFreeInfo) {
                System.err.printf("内存: used=%,dMB, free=%,dMB, total=%,dMB%n",
                        (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024,
                        runtime.freeMemory() / 1024 / 1024,
                        runtime.totalMemory() / 1024 / 1024);
            }
        }, 1, 1, TimeUnit.SECONDS);
    }

    // 记录一次请求
    public void increment(Supplier<?> supplier) {
        if (supplier != null) {
            supplier.get();
        }
        counter.incrementAndGet();
    }

    // 获取上一秒的QPS
    public long getQPS() {
        return lastQPS;
    }

    // 关闭计数器
    public void shutdown() {
        scheduler.shutdown();
    }

    // 手动重置计数器(通常不需要，因为会自动每秒重置)
    public void reset() {
        counter.set(0);
        lastQPS = 0;
    }

    public static void main(String[] args) {
        QPSCounter counter = new QPSCounter(true);

        AtomicLong secCounter = new AtomicLong(0);

        int threadCount = 4;
        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                for (;;) {
                    counter.increment(GlobalNumberGenerator::nextId);
                }
            }).start();
        }
        while (true) {
            // 每秒打印QPS
            LockSupport.parkNanos(1_000_000_000);
            System.out.println("执行第 " + secCounter.incrementAndGet() + "s, threads: " + threadCount + ", QPS: " + counter.getQPS());
        }
    }
}